package andev.schoolhelper.register;

import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import andev.aandroidlib.activity.ANetActivity;
import andev.schoolhelper.R;
import andev.schoolhelper.util.VolleyJSONRequest;

public class RegisterActivity extends ANetActivity {
    String UserName, Mail, inputCode, Password;
    private String code = "";
    private RequestQueue requestQueue;
    private EditText etEmail, etVerifyCode, etPassword;
    private Button btnGetVerifyCode, btnRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        setFallBack("返回");

        requestQueue = getAppRequestQueue();

        InitWidgets();
        InitETMailListener();
        InitGetCodeListener();
        InitRegisterListener();
    }

    private void InitWidgets() {
        etEmail = (EditText) findViewById(R.id.etEmail);
        etVerifyCode = (EditText) findViewById(R.id.etVerifyCode);
        etPassword = (EditText) findViewById(R.id.etPassword);

        btnGetVerifyCode = (Button) findViewById(R.id.btnGetVerifyCode);
        btnRegister = (Button) findViewById(R.id.btnRegister);
    }

    private void InitETMailListener() {
        etEmail.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                code = "1";
                etVerifyCode.setText("");
                etVerifyCode.setHint("邮箱已修改");
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private void InitGetCodeListener() {
        btnGetVerifyCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String mail = etEmail.getText().toString();
                if ("".equals(mail)) {
                    Toast toast;
                    toast = Toast.makeText(RegisterActivity.this, "输入邮箱再获取嘛", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                    return;
                }
                btnGetVerifyCode.setEnabled(false);
                btnGetVerifyCode.setText("正在获取...");

                String url = "http://angusphp.sinaapp.com/service/mobile_getverifycode_service.php?mail=" + mail;
                VolleyJSONRequest jsonObjectRequest;
                jsonObjectRequest =
                        new VolleyJSONRequest
                                (
                                        Method.GET,
                                        url,
                                        null,
                                        new Response.Listener<JSONObject>() {
                                            @Override
                                            public void onResponse(JSONObject response) {
                                                try {
                                                    RegisterActivity.this.code = response.getString("code");
                                                    if (RegisterActivity.this.code.equals("mail error")) {
                                                        Toast.makeText(RegisterActivity.this, "无效的邮箱", Toast.LENGTH_SHORT).show();
                                                        resetBtnGetVerifyCode();
                                                        return;
                                                    }
                                                    if (RegisterActivity.this.code.equals("pdo connect failed")) {
                                                        Toast.makeText(RegisterActivity.this, "服务器出错", Toast.LENGTH_SHORT).show();
                                                        resetBtnGetVerifyCode();
                                                        return;
                                                    }
                                                    if (RegisterActivity.this.code.equals("mail exist")) {
                                                        Toast.makeText(RegisterActivity.this, "邮箱已被使用", Toast.LENGTH_SHORT).show();
                                                        resetBtnGetVerifyCode();
                                                        return;
                                                    }
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                                RegisterActivity.this.setBtnDaoJiShi();
                                            }
                                        },
                                        new Response.ErrorListener() {
                                            @Override
                                            public void onErrorResponse(VolleyError error) {
                                            }
                                        }
                                );
                if (requestQueue != null && jsonObjectRequest != null) {
                    //requestQueue.add(jsonObjectRequest);
                }
            }
        });
    }

    protected void setBtnDaoJiShi() {
        final Handler handler = new Handler();
        Runnable runnable =
                new Runnable() {
                    int sec = 60;

                    @Override
                    public void run() {
                        if (sec > 0) {
                            RegisterActivity.this.btnGetVerifyCode.setText(sec + "s后重新获取");
                            sec--;
                            handler.postDelayed(this, 1000);
                        } else {
                            resetBtnGetVerifyCode();
                        }
                    }
                };
        handler.post(runnable);
    }

    private void resetBtnGetVerifyCode() {
        btnGetVerifyCode.setText("获取验证码");
        btnGetVerifyCode.setEnabled(true);
    }

    private void InitRegisterListener() {
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Mail = etEmail.getText().toString();
                inputCode = etVerifyCode.getText().toString();
                Password = etPassword.getText().toString();
                if (Mail.equals("")) {
                    Toast.makeText(RegisterActivity.this, "请输入邮箱", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (inputCode.equals("")) {
                    Toast.makeText(RegisterActivity.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (Password.equals("")) {
                    Toast.makeText(RegisterActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (Password.length() < 6) {
                    Toast.makeText(RegisterActivity.this, "密码长度至少6位", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (code.equals("")) {
                    Toast.makeText(RegisterActivity.this, "注册失败，与服务器连接异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!inputCode.equals(code)) {
                    Toast.makeText(RegisterActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                    return;
                }
                Register();
            }
        });

    }

    protected void Register() {
        Log.i("", "Register");
        String url = "http://angusphp.sinaapp.com/service/mobile_registerService.php";
        Map<String, String> params = new HashMap<String, String>();
        params.put("Password", Password);
        params.put("Mail", Mail);
        VolleyJSONRequest jsonObjectRequest;
        jsonObjectRequest =
                new VolleyJSONRequest
                        (
                                Method.POST,
                                url,
                                params,
                                new Response.Listener<JSONObject>() {
                                    @Override
                                    public void onResponse(JSONObject response) {
                                        String status = "";
                                        try {
                                            status = response.getString("status");
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        if (status.equals("")) {
                                            Toast.makeText(RegisterActivity.this, "注册失败，与服务器连接异常", Toast.LENGTH_SHORT).show();
                                            return;
                                        }
                                        if (status.equals("success")) {
                                            Toast.makeText(RegisterActivity.this, "注册成功，正在为你自动登陆", Toast.LENGTH_LONG).show();
                                            Bundle params = new Bundle();
                                            params.putString("username", Mail);
                                            params.putString("password", Password);
                                            finishSelfWithParams(params);
                                            return;
                                        } else {
                                            Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
                                            return;
                                        }
                                    }
                                },
                                new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
                                    }
                                }
                        );
        if (requestQueue != null && jsonObjectRequest != null) {
            requestQueue.add(jsonObjectRequest);
        }
    }

}
